<?php

namespace app\admin\model;

use Exception;
use think\Model;
use think\Db;

class Questiongroup extends Model
{

    

    

    // 表名
    protected $name = 'question_group';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];
    

    
    public function getStatusList()
    {
        return ['normal' => __('Status normal'), 'hidden' => __('Status hidden')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }





    /**
     * 固定选题保存 刷题组卷
     * @param mixed $data 
     * @return void 
     * @throws Exception 
     */
    public function addFixQuestion($data)
    {
        $questions = $data['questions'];
        $questionGroup = $data['questionGroup'];
        # 把题库数据 写入 考试表
        $insert = [];
        try {
            foreach ($questions as $key => $question) {
                // 检查原题目是否存在
                $questionInfo = Db::name('question')->where('id', $question["id"])->find();
                // 检查题目是否已经在该试卷中存在，避免重复添加
                $existingQuestion = Db::name('question_paper')->where([
                    'question_group_id' => $questionGroup['id'],
                    'question_id' => $question['id']
                ])->find();
                if (!$existingQuestion) {
                    $insert[] = [
                        'question_group_id' => $questionGroup['id'],
                        'question_id' => $question['id'],
                        'answer_config' => is_array($question['answer']) ? json_encode($question['answer'], JSON_UNESCAPED_UNICODE) : $question['answer'],
                        'createtime' => time(),
                    ];
                } else {
                    continue;
                }
            }
            if (!empty($insert)) {
                Db::name('question_paper')->insertAll($insert);
            }
        } catch (\Exception $e) {
            \think\Log::error("添加固定题目异常，试卷ID: " . $paper['id'] . ", 错误: " . $e->getMessage());
            throw $e;
        }
    }




}
